<?php

namespace App\Logics;


use App\Models\Student;
use App\Models\User;
use App\Service\Ali\AliCaptcha;
use App\Service\Base\Logic;
use App\Service\WeChat\MiniWx;
use App\Service\WeChat\OpenWx;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Str;

class AccountLogic extends Logic
{

    // 登录注册操作

    // 获取 token
    public function token()
    {
        $uid    = $this->option()->getData('uid', 0, 'intval');
        $mobile = $this->option()->getData('mobile', '', 'trim');
        if(empty($uid) && empty($mobile)){
            return $this->_returnFail('获取指定用户的token！');
        }

        $where = [];
        if($uid){
            $where = ['id' => $uid];
        }
        if($mobile){
            $where = ['mobile' => $mobile];
        }

        $userDb = new User();
        $info   = $userDb->where($where)->first();
        if(empty($info)){
            return $this->_returnFail('用户不存在！');
        }
        if($info->status === 0){
            return $this->_returnFail('用户被禁用！');
        }

        $info   = $info->toArray();
        $token  = Crypt::encryptString(json_encode($info, JSON_UNESCAPED_UNICODE));
        $result = ['token' => $token, 'user' => $info,];

        return $result;
    }


    // 登录：手机号 + 验证码（只登录，不注册）（pc端使用：手机号+密码+验证码）
    public function mobileLogin()
    {
        $option   = $this->option();
        $username = $option->getData('username', null, 'trim');
        $password = $option->getData('password', null, 'trim');
        $mobile   = $option->getData('mobile', null, 'trim');
        $captcha  = $option->getData('captcha', null, 'trim');  // 验证码（短信验证码）
        if(empty($mobile)){
            return $this->_returnFail('请输入手机号！！');
        }
        if(empty($password)){
            return $this->_returnFail('请输入密码！！');
        }
        if(empty($captcha)){
            return $this->_returnFail('请输入验证码！！');
        }

        // 验证验证码
        $login_code = Session::get('organ_code');
        // var_dump(Session::all());  // 前台没有验证码的session 输出所有的session，没有找到有对应验证码
        //if(!empty($login_code)){ }
        if($captcha != strtolower($login_code)){
            return $this->_returnFail('验证码输入不正确，请重新输入！！'.$login_code);
        }

        // 获取登录的用户信息
        $userDb = new User();
        $info   = $userDb->login($mobile, $password, 'mobile');
        if($info === false){
            return $this->_returnFail($userDb->getError());
        }

        return $info;
    }


    // 小程序登录（没有，则注册）（小程序端使用：手机号+wx_code）
    public function miniLoginWxCode()
    {
        $option = $this->option();
        $mobile = $option->getData('mobile', null, 'trim');
        $wxCode = $option->getData('wx_code', null, 'trim');  // 微信code用于获取openID
        if(empty($wxCode)){
            return $this->_returnFail('请先获取微信code！！');
        }
        if(empty($mobile)){
            return $this->_returnFail('请输入手机号！！');
        }

        // 获取微信openID
        /**
         *  var userInfo = res.userInfo
         * var nickName = userInfo.nickName
         * var avatarUrl = userInfo.avatarUrl
         * var gender = userInfo.gender //性别 0：未知、1：男、2：女
         * var province = userInfo.province
         * var city = userInfo.city
         * var country = userInfo.country
         */
        //$wx   = new OpenWx();
        //$res  = $wx->getUserByMini($wxCode);

        $mini = new MiniWx();
        $data = $mini->getOpenidByMini($wxCode);
        if(empty($data)){
            return $this->_returnFail('获取微信信息失败！！');
        }
        if(!empty($data['errcode'])){
            return $this->_returnFail($data['errmsg']);
        }

        Log::info('Request | 微信小程序请求openID返回 |', $data);
        $openid   = $data['openid'];
        $_key     = $data['session_key'];
        $head_img = $data['avatarUrl'] ?? '';
        $nickname = $data['nickName'] ?? '';

        // 判断微信是否存在
        $userDb = new User();
        $where  = [['openid', '=', $openid], ['status', '>=', 0]];
        $info   = $userDb->isCache(true)->oneFind($where);
        if(empty($info)){
            // 如果没有 则注册
            $salt  = Str::random(4);
            $salt  = $userDb->salt(6, true);
            $_pass = $userDb->add_md5(123456, $salt);  // 密码
            $data  = ['mobile' => $mobile, 'openid' => $openid, 'salt' => $salt, 'password' => $_pass,];
            if(!empty($head_img)){
                $data['head_img'] = $head_img;
            }
            if(!empty($nickname)){
                $data['nickname'] = $nickname;
            }
            $uid = $userDb->oneAdd($data);
            // 重新查询
            $info = $userDb->isCache(true)->oneFind(['mobile' => $mobile]);
            // 更新学员信息
            $this->updateStudent($info['id'], $mobile);
        }
        if($info['status'] === 0){
            return $this->_returnFail('对不起，您已经被禁用！！');
        }

        // 更新头像  和 名称
        $userId = $info['id'];
        $updata = ['last_ip' => $option->getIp(), 'last_time' => LARAVEL_TIME,];
        if((!empty($head_img)) && empty($info['head_img'])){
            $updata['head_img'] = $head_img;
        }
        if(empty($info['nickname'])){
            if(!empty($nickname)){
                $updata['nickname'] = $nickname;
            } else{
                $mobile   = $data['mobile'] ?? ($info['mobile'] ?: 0);
                $number   = '0000'.($info['id'] + $mobile);
                $username = $info['salt'].substr($number, -4);
                $updata   = ['nickname' => $username];
                if(empty($info['username'])){
                    $updata['username'] = $username;
                }
            }
        }

        // 更新
        $rst = $userDb->where('id', $userId)->update($updata);
        if($rst === false){
            return $this->_returnFail($userDb->getError());
        }

        // 清理缓存
        $userDb->deleteCacheShow($info, $updata);

        // 返回
        //$user   = ['id' => $userId, 'nickname' => $info['email'], 'mobile' => $info['mobile']];
        $token  = Crypt::encryptString(json_encode($info, JSON_UNESCAPED_UNICODE));
        $result = ['token' => $token, 'user' => $info,];

        return $result;
    }


    // 小程序注册（没有，则注册）（小程序端使用：手机号+openID+头像+昵称）
    public function miniRegister()
    {
        $option   = $this->option();
        $openid   = $option->getData('openid', null, 'trim');
        $mobile   = $option->getData('mobile', null, 'trim');
        $head_img = $option->getData('head_img', null, 'trim');
        $nickname = $option->getData('nickname', null, 'trim');
        if(empty($mobile)){
            return $this->_returnFail('请输入手机号！！');
        }
        if(empty($openid)){
            return $this->_returnFail('请输入openid！！');
        }

        // 获取登录的用户信息
        $userDb = new User();
        $where  = [['openid', '=', $openid], ['status', '>=', 0]];
        $info   = $userDb->isCache(true)->oneFind($where);
        if(empty($info)){
            // 如果没有 则注册
            $salt  = Str::random(4);
            $salt  = $userDb->salt(6, true);
            $_pass = $userDb->add_md5(123456, $salt);  // 密码
            $data  = ['mobile' => $mobile, 'openid' => $openid, 'salt' => $salt, 'password' => $_pass,];
            if(!empty($head_img)){
                $data['head_img'] = $head_img;
            }
            if(!empty($nickname)){
                $data['nickname'] = $nickname;
            }
            $uid = $userDb->oneAdd($data);
            // 重新查询
            $info = $userDb->isCache(true)->oneFind($where);
        }

        // 更新头像  和 名称
        $userId = $info['id'];
        $updata = ['last_ip' => $option->getIp(), 'last_time' => LARAVEL_TIME,];
        if((!empty($head_img)) && empty($info['head_img'])){
            $updata['head_img'] = $head_img;
        }
        if((!empty($nickname)) && empty($info['nickname'])){
            $updata['nickname'] = $nickname;
        }
        if((!empty($mobile)) && empty($info['mobile'])){
            $username = $info['salt'].substr($info['id'] + $mobile, -4);
            // 更新
            $updata['mobile']   = $mobile;
            $updata['username'] = $username;
            $updata['nickname'] = $username;

            // 更新学员信息
            $this->updateStudent($userId, $mobile);
        }
        if(empty($updata['nickname']) && empty($info['nickname'])){
            $mobile   = $info['mobile'] ?: ($mobile ?: 0);
            $number   = '0000'.($info['id'] + $mobile);
            $username = $info['salt'].substr($number, -4);
            $updata   = ['nickname' => $username];
            if(empty($info['username'])){
                $updata['username'] = $username;
            }
            if($mobile && empty($updata['mobile'])){
                $updata['mobile'] = $mobile;
            }
        }

        // 执行更新
        $rst = $userDb->where('id', $userId)->update($updata);
        if($rst === false){
            return $this->_returnFail($userDb->getError());
        }

        // 返回
        //$user   = ['id' => $userId, 'nickname' => $info['email'], 'mobile' => $info['mobile']];
        $token  = Crypt::encryptString(json_encode($info, JSON_UNESCAPED_UNICODE));
        $result = ['token' => $token, 'user' => $info,];

        return $result;
    }

    // 使用 openID 只登录，不注册
    public function openidLogin()
    {
        $option = $this->option();
        $openid = $option->getData('openid', null, 'trim');
        if(empty($openid)){
            return $this->_returnFail('请输入openid！！');
        }

        // 获取登录的用户信息
        $userDb = new User();
        $where  = [['openid', '=', $openid], ['status', '>=', 0]];
        $info   = $userDb->isCache(true)->oneFind($where);
        if(empty($info)){
            //return $this->_returnFail($userDb->getError());
            $salt  = Str::random(4);
            $salt  = $userDb->salt(6, true);
            $_pass = $userDb->add_md5(123456, $salt);  // 密码
            $data  = ['openid' => $openid, 'salt' => $salt, 'password' => $_pass,];
            $uid   = $userDb->oneAdd($data);
            // 重新查询
            $info = $userDb->isCache(true)->oneFind($where);
        }

        // 更新头像  和 名称
        $userId = $info['id'];
        $updata = ['last_ip' => $option->getIp(), 'last_time' => LARAVEL_TIME,];
        if(empty($info['nickname'])){
            $mobile   = $data['mobile'] ?? ($info['mobile'] ?: 0);
            $number   = '0000'.($info['id'] + $mobile);
            $username = $info['salt'].substr($number, -4);
            $updata   = ['nickname' => $username];
            if(empty($info['username'])){
                $updata['username'] = $username;
            }
        }
        // 更新 登录信息
        $rst = $userDb->where('id', $userId)->update($updata);
        if($rst === false){
            return $this->_returnFail($userDb->getError());
        }

        // 重新查询
        $info = $userDb->isCache(true)->oneFind($where);

        // 返回
        $token  = Crypt::encryptString(json_encode($info, JSON_UNESCAPED_UNICODE));
        $result = ['token' => $token, 'user' => $info,];

        return $result;
    }

    // 使用 加密数据与openID登录
    public function decodeLogin()
    {
        $option  = $this->option();
        $openid  = $option->getData('openid', null, 'trim');
        $iv      = $option->getData('iv', null, 'trim');
        $key     = $option->getData('session_key', null, 'trim');
        $encrypt = $option->getData('encrypted', null, 'trim');
        if(empty($openid)){
            return $this->_returnFail('请输入openid！！');
        }
        if(empty($encrypt) || empty($key) || empty($iv)){
            return $this->_returnFail('请传递解析参数！！');
        }

        // 解密获取手机号
        $result = $this->miniDecrypt($encrypt, $iv, $key);
        $res    = json_decode($result, true);
        if(empty($res['phoneNumber'])){
            return $this->_returnFail('手机号解密获取失败！！');
        }


        // 获取登录的用户信息
        $mobile = $res['phoneNumber'];
        $userDb = new User();
        $where  = [['openid', '=', $openid], ['status', '>=', 0]];
        $info   = $userDb->isCache(true)->oneFind($where);
        if(empty($info)){
            $salt  = Str::random(4);
            $salt  = $userDb->salt(6, true);
            $_pass = $userDb->add_md5(123456, $salt);  // 密码
            $data  = ['mobile' => $mobile, 'openid' => $openid, 'salt' => $salt, 'password' => $_pass,];
            $uid   = $userDb->oneAdd($data);
            // 重新查询
            $info = $userDb->isCache(true)->oneFind(['id' => $uid]);
        }

        // 更新 用户登录时间
        //   如果用户没有名称 则重新生成名次
        $userId = $info['id'];
        $updata = ['last_ip' => $option->getIp(), 'last_time' => LARAVEL_TIME,];
        if(empty($info['nickname'])){
            $mobile   = $data['mobile'] ?? ($info['mobile'] ?: 0);
            $number   = '0000'.($info['id'] + $mobile);
            $username = $info['salt'].substr($number, -4);
            $updata   = ['nickname' => $username];
            if(empty($info['username'])){
                $updata['username'] = $username;
            }
        }
        // 更新 登录信息
        $rst = $userDb->where('id', $userId)->update($updata);
        if($rst === false){
            return $this->_returnFail($userDb->getError());
        }

        // 更新学员信息
        $this->updateStudent($userId, $mobile);

        // 重新查询
        $userDb->deleteCacheShow($info);
        $info = $userDb->isCache(true)->oneFind($where);

        // 返回
        $token  = Crypt::encryptString(json_encode($info, JSON_UNESCAPED_UNICODE));
        $result = ['token' => $token, 'user' => $info,];

        return $result;
    }


    // 微信公众号登录（没有，则注册）（暂未使用）
    public function _wxLogin()
    {
        $option = $this->option();
        $wxCode = $option->getData('wx_code', null, 'trim');  // 微信code用于获取openID
        if(empty($wxCode)){
            return $this->_returnFail('请先获取微信code！！');
        }

        // 获取微信openID
        $wx   = new OpenWx();
        $res  = $wx->getAccessToken($wxCode);
        $data = json_decode($res, true);

        // 获取微信用户信息
        $openid = $data['openid'];
        $_token = $data['access_token'];
        $res    = $wx->getUser($_token, $openid);
        $data   = json_decode($res, true);


        Log::info('Request | 微信公众号请求用户信息返回 |', $data);
        $head_img = $data['avatarUrl'];
        $nickname = $data['nickName'];
        $mobile   = $data['mobile'];

        // 判断微信是否存在
        $userDb = new User();
        $where  = [['openid', '=', $openid], ['status', '>=', 0]];
        $info   = $userDb->isCache(true)->oneFind($where);
        if(empty($info)){
            // 如果没有 则注册
            $salt  = Str::random(4);
            $salt  = $userDb->salt(6, true);
            $_pass = $userDb->add_md5(123456, $salt);  // 密码
            $data  = ['mobile' => $mobile, 'openid' => $openid, 'salt' => $salt, 'password' => $_pass,];
            if(!empty($head_img)){
                $data['head_img'] = $head_img;
            }
            if(!empty($nickname)){
                $data['nickname'] = $nickname;
            }
            $uid = $userDb->oneAdd($data);
            // 重新查询
            $info = $userDb->isCache(true)->oneFind(['mobile' => $mobile]);
        }
        if($info['status'] === 0){
            return $this->_returnFail('对不起，您已经被禁用！！');
        }

        // 更新头像  和 名称
        $userId = $info['id'];
        $updata = ['last_ip' => $option->getIp(), 'last_time' => LARAVEL_TIME,];
        if((!empty($head_img)) && empty($info['head_img'])){
            $updata['head_img'] = $head_img;
        }
        if((!empty($nickname)) && empty($info['nickname'])){
            $updata['nickname'] = $nickname;
        }

        // 更新
        $rst = $userDb->where('id', $userId)->update($updata);
        if($rst === false){
            return $this->_returnFail($userDb->getError());
        }

        // 清理缓存
        $userDb->deleteCacheShow($info, $updata);

        // 返回
        //$user   = ['id' => $userId, 'nickname' => $info['email'], 'mobile' => $info['mobile']];
        $token  = Crypt::encryptString(json_encode($info, JSON_UNESCAPED_UNICODE));
        $result = ['token' => $token, 'user' => $info,];

        return $result;
    }

    ##########################################################################################################
    // 获取 openID:o4H167e6PNOYgpwJKihvj1ZdqIk4
    public function getMiniOpenid()
    {
        $option = $this->option();
        $wxCode = $option->getData('wx_code', null, 'trim');  // 微信code用于获取openID
        if(empty($wxCode)){
            return $this->_returnFail('请先获取微信code！！');
        }

        $mini = new MiniWx();
        $res  = $mini->getOpenidByMini($wxCode);

        //$res = $mini->_getOpenid($token, $code);

        return $res;
    }

    // 获取
    public function getMiniPhone()
    {
        $option = $this->option();
        $code   = $option->getData('code', null, 'trim');
        $openid = $option->getData('openid', null, 'trim');
        if(empty($openid)){
            return $this->_returnFail('请先获取微信openID！！');
        }
        if(empty($code)){
            return $this->_returnFail('请先获取微信code！！');
        }

        $mini   = new MiniWx();
        $_token = $mini->getAccessToken();
        $res    = $mini->getPhoneByMini($_token, $openid, $code);

        //$res = $mini->_getOpenid($token, $code);

        return $res;
    }

    //  解析小程序信息
    public function miniDecode()
    {
        $code    = '56bf7db84a7a9ec86728ba7dfe05ab5d863a73104cce00d104d4e16b0398e26c';
        $encrypt = 'hAnN9iW74tRsnnlfabGN+je8oulDTsNymmWT8+Z8thdckwDVa5m2WgN9uh/W+tz6VXcwKPB8FfmWc1AulqTHsRwkz6tQpj/kLivcugiZQDTQc3f1EuBGOtiNN8JRODwnmx2xn8cx8276admAVjsnr5vcwTic9c9Mn00b++IlqTeOYWcgAxGljupymKSWCu4Mr05t3ARlzw2Cl/sgAFwytQ==';
        $iv      = 'DlIae/I1SogwLN51DEz6Xw==';
        $key     = 'NNoYdVDI8qXT+shOMF6krQ==';

        $option  = $this->option();
        $iv      = $option->getData('iv', null, 'trim');
        $key     = $option->getData('session_key', null, 'trim');
        $encrypt = $option->getData('encrypted', null, 'trim');
        if(empty($encrypt) || empty($key) || empty($iv)){
            return $this->_returnFail('请传递解析参数！！');
        }

        $res = $this->miniDecrypt($encrypt, $iv, $key);
        $this->log('json', $res);
        $res = json_decode($res, true);
        $this->log($res, '数组');

        return $res;
    }

    //  解析小程序信息
    public function miniDecodeTest()
    {
        $code    = '56bf7db84a7a9ec86728ba7dfe05ab5d863a73104cce00d104d4e16b0398e26c';
        $encrypt = 'hAnN9iW74tRsnnlfabGN+je8oulDTsNymmWT8+Z8thdckwDVa5m2WgN9uh/W+tz6VXcwKPB8FfmWc1AulqTHsRwkz6tQpj/kLivcugiZQDTQc3f1EuBGOtiNN8JRODwnmx2xn8cx8276admAVjsnr5vcwTic9c9Mn00b++IlqTeOYWcgAxGljupymKSWCu4Mr05t3ARlzw2Cl/sgAFwytQ==';
        $iv      = 'DlIae/I1SogwLN51DEz6Xw==';
        $key     = 'NNoYdVDI8qXT+shOMF6krQ==';


        $encrypt = 'hAnN9iW74tRsnnlfabGN+je8oulDTsNymmWT8+Z8thdckwDVa5m2WgN9uh/W+tz6VXcwKPB8FfmWc1AulqTHsRwkz6tQpj/kLivcugiZQDTQc3f1EuBGOtiNN8JRODwnmx2xn8cx8276admAVjsnr5vcwTic9c9Mn00b++IlqTeOYWcgAxGljupymKSWCu4Mr05t3ARlzw2Cl/sgAFwytQ==';
        $iv      = 'DlIae/I1SogwLN51DEz6Xw==';
        $key     = 'NNoYdVDI8qXT+shOMF6krQ==';
        if(empty($encrypt) || empty($key) || empty($iv)){
            return $this->_returnFail('请传递解析参数！！');
        }

        $res = $this->miniDecrypt($encrypt, $iv, $key);
        $this->log('json', $res);
        $res = json_decode($res, true);
        $this->log($res, '数组');

        return $res;
    }

    ##########################################################################################################
    ## 阿里云弹出式验证码 验证
    public function onAliCaptcha()
    {
        $opt     = $this->option();
        $param   = $opt->getData('captchaVerifyParam', null, 'trim');
        $sceneId = 'qonabfwj';  // 场景ID。根据步骤二新建验证场景后，您可以在验证码场景列表，获取该场景的场景ID

        /*$curl = new Curl();
        $post = ['CaptchaVerifyParam' => $param, 'SceneId' => $sceneId];
        $url  = 'https://captcha.cn-shanghai.aliyuncs.com/VerifyIntelligentCaptcha';
        $res  = $curl->post($post)->request($url);
        $res  = (array)simplexml_load_string($res, 'SimpleXMLElement', LIBXML_NOCDATA);*/

        // var_dump($res);
        //$AliCaptcha = new AliCaptcha();
        $res = AliCaptcha::main($param);


        return $res;
    }

    ##########################################################################################################
    // 假设你有一个WechatService类来处理微信相关的逻辑
    public function getSessionKeyAndOpenid($code)
    {
        $url      = "https://api.weixin.qq.com/sns/jscode2session";
        $params   = [
            'appid'      => config('wechat.mini_program.app_id'),
            'secret'     => config('wechat.mini_program.secret'),
            'js_code'    => $code,
            'grant_type' => 'authorization_code',
        ];
        $response = json_decode(file_get_contents($url.'?'.http_build_query($params)), true);
        if(isset($response['errcode'])){
            throw new Exception($response['errmsg']);
        }

        return $response;
    }

    // 获取小程序各种数据的 加密（所有数据来源于小程序传递过来的）
    public function miniEncrypt($data, $iv, $key)
    {
        $block_size = 16;
        //补位处理
        $padding = $block_size - strlen($data) % $block_size;
        $data    .= str_repeat(chr($padding), $padding);
        //加密
        $encrypted = openssl_encrypt($data, 'AES-128-CBC', $key, OPENSSL_RAW_DATA, $iv);

        return base64_encode($encrypted);
    }

    // 获取小程序各种数据的 解密（所有数据来源于小程序传递过来的）
    public function miniDecrypt($encrypted, $iv, $key)
    {
        $aesKey    = base64_decode($key);
        $aesIV     = base64_decode($iv);
        $encrypted = base64_decode($encrypted);
        $decrypted = openssl_decrypt($encrypted, 'AES-128-CBC', $aesKey, OPENSSL_RAW_DATA, $aesIV);

        $block_size = 16;
        //去除补位信息
        $padding = ord(substr($decrypted, -1));
        if($padding < 1 || $padding > $block_size){
            $padding = 0;
        }
        $decrypted = substr($decrypted, 0, strlen($decrypted) - $padding);

        return $decrypted;
    }

    /**
     * 对明文进行加密
     * @param string $text 需要加密的明文
     * @return string 加密后的密文
     */
    public function encrypt2($text, $appid)
    {
        try{
            //获得16位随机字符串，填充到明文之前
            $random      = $this->getRandomStr();//"aaaabbbbccccdddd";
            $text        = $random.pack("N", strlen($text)).$text.$appid;
            $iv          = substr($this->key, 0, 16);
            $pkc_encoder = new PKCS7Encoder;
            $text        = $pkc_encoder->encode($text);
            $encrypted   = openssl_encrypt($text, 'AES-256-CBC', substr($this->key, 0, 32), OPENSSL_ZERO_PADDING, $iv);

            return array(ErrorCode::$OK, $encrypted);
        } catch(Exception $e){
            //print $e;
            return array(ErrorCode::$EncryptAESError, null);
        }
    }

    /**
     * 对密文进行解密
     * @param string $encrypted 需要解密的密文
     * @return string 解密得到的明文
     */
    public function decrypt2($encrypted, $appid)
    {
        try{
            $iv        = substr($this->key, 0, 16);
            $decrypted = openssl_decrypt($encrypted, 'AES-256-CBC', substr($this->key, 0, 32), OPENSSL_ZERO_PADDING, $iv);
        } catch(Exception $e){
            return array(ErrorCode::$DecryptAESError, null);
        }
        try{
            //去除补位字符
            $pkc_encoder = new PKCS7Encoder;
            $result      = $pkc_encoder->decode($decrypted);
            //去除16位随机字符串,网络字节序和AppId
            if(strlen($result) < 16)
                return "";
            $content     = substr($result, 16, strlen($result));
            $len_list    = unpack("N", substr($content, 0, 4));
            $xml_len     = $len_list[1];
            $xml_content = substr($content, 4, $xml_len);
            $from_appid  = substr($content, $xml_len + 4);
            if(!$appid)
                $appid = $from_appid;
            //如果传入的appid是空的，则认为是订阅号，使用数据中提取出来的appid
        } catch(Exception $e){
            //print $e;
            return array(ErrorCode::$IllegalBuffer, null);
        }
        if($from_appid != $appid)
            return array(ErrorCode::$ValidateAppidError, null);

        //不注释上边两行，避免传入appid是错误的情况
        return array(0, $xml_content, $from_appid);
        //增加appid，为了解决后面加密回复消息的时候没有appid的订阅号会无法回复
    }

    // 更新学员状态
    protected function updateStudent($uid, $mobile)
    {
        $studentDb = new Student();
        $sInfo     = $studentDb->where('mobile', $mobile)->where('status', '>=', 0)->first();
        if($sInfo){
            $studentDb->where('id', $sInfo->id)->update(['person_uid' => $uid, 'status' => 1]);
        }

        $studentDb->deleteCacheShow($sInfo);
    }

}



